import functools
import inspect
import logging
import time

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def trace(func):
    """"""
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        stack = inspect.stack()
        caller_frame=stack[1]
        caller_name = caller_frame.function

        #记录调用信息
        logger.info(f"Function: {func.__name__} called by {caller_name} with args {args},kwargs {kwargs}")

        #记录开始时间
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        logger.info(f"Function {func.__name__} executed in {end_time-start_time} seconds")
        return result
    return wrapper

class DynamicInvoker:
    """
    动态调用类：使用反射机制
    """
    def __init__(self,target):
        self.target = target

    def invoke(self,method_name,*args,**kwargs):
        """
        调用目标对象的指定方法
        :param method_name:
        :param args:
        :param kwargs:
        :return:
        """
        if hasattr(self.target,method_name):
            method = getattr(self.target,method_name)
            if callable(method):
                logger.info(f"Invoking {method_name} with args {args},kwargs {kwargs}")
                return method(*args,**kwargs)
            else:
                logger.error("eeoorr")

class SampleClass:
    @trace
    def method_one(self,x):
        return x*2

    @trace
    def method_two(self,y):
        time.sleep(1)
        return y+100


if __name__ == "__main__":
    sample = SampleClass()
    invoke = DynamicInvoker(sample)
    print(invoke.invoke("method_one",1))
